package java_thinking.unit_21._21_13;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Desc:   13.4    带有时间限制的加锁
 * @author: cww
 * @DateTime: 2019/6/26 20:30
 */

public class TimedLocking {
    private Lock lock = new ReentrantLock();
    public boolean trySendOnSharedLine(String message, long timeout, TimeUnit unit) throws InterruptedException {
        long nanosToLock = unit.toNanos(timeout) - estimatedNanosToSend(message);
        /**
         * 带有时间限制的操作中实现独占加锁
         */
        if (!lock.tryLock(nanosToLock, TimeUnit.NANOSECONDS)) {
            return false;
        }
        try {
            return sendOnSharedLine(message);
        } finally {
            lock.unlock();
        }
    }

    private boolean sendOnSharedLine(String message) {
        /* send something */
        return true;
    }
    long estimatedNanosToSend(String message) {
        return message.length();
    }

}
